# -*- coding: utf-8 -*-
import sys
from WXBizMsgCrypt import WXBizMsgCrypt
import xml.etree.cElementTree as ET
import time
import urllib,urllib2,json
import redis_data

from palmgo.settings import sCorpID,sEncodingAESKey,sToken
from palmgo.settings import corpid,corpsecret

class weixin_main(object):
	def __init__(self):
		self.wxcpt=WXBizMsgCrypt(sToken,sEncodingAESKey,sCorpID)
	def check_signature(self,signature,timestamp,nonce,echostr):

		ret,sEchoStr=self.wxcpt.VerifyURL(signature,timestamp,nonce,echostr)
		if(ret != 0):
			print "ERR: VerifyURL ret: " + str(ret)
			return

				#返回，否则程序会死掉

			#sys.exit(1)
		else:
			return sEchoStr   ##回调验证 返回明文

	def Decrypt(self,body,signature,timestamp,nonce):
		self.timestamp=timestamp
		self.nonce=nonce
		ret,sMsg=self.wxcpt.DecryptMsg(body,signature,self.timestamp,self.nonce)
		if( ret != 0 ):
			print "ERR: DecryptMsg ret: " + str(ret)
			return
		#sys.exit(1)
		#     logging.info(sMsg)
		self.xml_tree = ET.fromstring(sMsg)    ##sMsg  解密后的XML
		print sMsg

		self.msgtype=self.xml_tree.find("MsgType").text
		self.touser=self.xml_tree.find("ToUserName").text
		self.fromuser=self.xml_tree.find("FromUserName").text
		self.AgentID=self.xml_tree.find("AgentID").text
		self.msgtype=self.xml_tree.find("MsgType").text
		# self.event=self.xml_tree.find("Event").text

		return self.msgtype,self.xml_tree

	def Encrypt_new(self,title,url,picurl):
		sRespData = "<xml><ToUserName><![CDATA[{0}]]></ToUserName><FromUserName><![CDATA[{1}]]></FromUserName><CreateTime>{2}</CreateTime>\
		<MsgType><![CDATA[news]]></MsgType><ArticleCount>6</ArticleCount>\
		<Articles>\
		<item><Title><![CDATA[{3}]]></Title> <Description><![CDATA[{4}]]>\
		</Description><PicUrl><![CDATA[{5}]]></PicUrl><Url><![CDATA[{6}]]></Url></item>\
		<item><Title><![CDATA[{3}]]></Title> <Description><![CDATA[{4}]]>\
		</Description><PicUrl><![CDATA[{5}]]></PicUrl><Url><![CDATA[{6}]]></Url></item>\
		<item><Title><![CDATA[{3}]]></Title> <Description><![CDATA[{4}]]>\
		</Description><PicUrl><![CDATA[{5}]]></PicUrl><Url><![CDATA[{6}]]></Url></item>\
		<item><Title><![CDATA[{3}]]></Title> <Description><![CDATA[{4}]]>\
		</Description><PicUrl><![CDATA[{5}]]></PicUrl><Url><![CDATA[{6}]]></Url></item>\
		<item><Title><![CDATA[{3}]]></Title> <Description><![CDATA[{4}]]>\
		</Description><PicUrl><![CDATA[{5}]]></PicUrl><Url><![CDATA[{6}]]></Url></item>\
		<item><Title><![CDATA[{3}]]></Title> <Description><![CDATA[{4}]]>\
		</Description><PicUrl><![CDATA[{5}]]></PicUrl><Url><![CDATA[{6}]]></Url></item>\
		</Articles></xml>".\
			format(self.fromuser,self.touser,str(int(time.time())),title,time.strftime('%Y-%m-%d',time.localtime(time.time()-24*60*60))+'日报',picurl,url)
		ret,sEncryptMsg=self.wxcpt.EncryptMsg(sRespData, self.nonce, self.timestamp)
		#print sRespData
		if( ret != 0 ):
			print ( "ERR: EncryptMsg ret: " + str(ret))
			sys.exit(1)
		return sEncryptMsg

	def Encrypt_text(self,content):
		sRespData = "<xml><ToUserName><![CDATA[{0}]]></ToUserName><FromUserName><![CDATA[{1}]]></FromUserName><CreateTime>{2}</CreateTime>\
		<MsgType><![CDATA[{3}]]></MsgType><Content><![CDATA[{4}]]></Content></xml>".\
			format(self.fromuser,self.touser,str(int(time.time())),'text',content)

		ret,sEncryptMsg=self.wxcpt.EncryptMsg(sRespData, self.nonce, self.timestamp)
		#print sRespData
		if( ret != 0 ):
			print ( "ERR: EncryptMsg ret: " + str(ret))
			sys.exit(1)
		return sEncryptMsg

#主动发送消息
class send_message(object):
	def __init__(self):  ##初始化获取 access_token
		self.rs=redis_data.redis_data()  ##从redis提取access_token 有效时间7200

		key='token'
		token_dict=self.rs.key_output(key)
		print token_dict
		if not token_dict:   ##如果没有 重新获取，并导入
			self.access_token=self.get_token()
			token_dict={'access_token':self.access_token,'createtime':int(time.time())}
			self.rs.key_import(key,token_dict)
			return
		else:
			token_dict=eval(token_dict)
			self.access_token=token_dict['access_token']  ##获取缓存中，如果下面 if成立，则会覆盖
			if time.time() - token_dict['createtime'] > 7000:  ##如果超时，获取并导入，有效时间7200秒
				self.access_token=self.get_token()
				token_dict={'access_token':self.access_token,'createtime':int(time.time())}
				self.rs.key_import(key,token_dict)
			return

	def return_token(self):  ##给 SDK 调用access_token使用
		return self.access_token


	def get_token(self):
		self.baseurl = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={0}&corpsecret={1}'.format(corpid, corpsecret)
		request = urllib2.Request(self.baseurl)
		response = urllib2.urlopen(request)
		ret = response.read().strip()
		ret = json.loads(ret)
		if ret["errcode" ] == 0:
			return ret.get('access_token')
		else:
			print 'err'
			sys.exit(0)

	def send_data(self,message,tousername):
		data={
		   "touser": tousername,
		   "toparty": "",
		   "totag": "",
		   "msgtype": "text",
		   "agentid": "1",   ##不 指定，则发送至企业助手
		   "text": {
			   "content":message}
		   }
		print 'message'+message
		self.baseurl="https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={0}".format(self.access_token)

		req = urllib2.Request(self.baseurl)
		req.add_header('Content-Type', 'application/json')
		req.add_header('encoding', 'utf-8')
		data=json.dumps(data,ensure_ascii=False)
		f=urllib2.urlopen(req,data)

		return f.read()

import random,hashlib
import string

class sdk(object):
	def __init__(self):
		self.rs=redis_data.redis_data()  ##从redis提取ticket 有效时间7200

		key='ticket'
		ticket_dict=self.rs.key_output(key)
		print ticket_dict
		if not ticket_dict:   ##如果没有 重新获取，并导入
			self.ticket=self.get_ticket()
			ticket_dict={'ticket':self.ticket,'createtime':int(time.time())}
			self.rs.key_import(key,ticket_dict)
			return
		else:
			ticket_dict=eval(ticket_dict)
			self.ticket=ticket_dict['ticket']  ##获取缓存中，如果下面 if成立，则会覆盖
			if time.time() - ticket_dict['createtime'] > 7000:  ##如果超时，获取并导入，有效时间7200秒
				self.ticket=self.get_ticket()
				ticket_dict={'ticket':self.ticket,'createtime':int(time.time())}
				self.rs.key_import(key,ticket_dict)
			return


	def get_ticket(self):
		wx=send_message()
		self.access_token=wx.return_token()

		self.baseurl="https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token={0}".format(self.access_token)
		request = urllib2.Request(self.baseurl)
		response = urllib2.urlopen(request)
		ret = response.read().strip()
		ret = json.loads(ret)
		print ret
		if ret[u"errcode"] == 0:
			return ret['ticket']
		else:
			print 'err'
			sys.exit(0)

	def get_signature(self,timestamp,url):
		nonceStr= ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(15))

		self.ret = {
            'nonceStr': nonceStr,
            'jsapi_ticket': self.ticket,
            'timestamp':timestamp,
            'url': url
        }
		signature_str = '&'.join(['%s=%s' % (key.lower(), self.ret[key]) for key in sorted(self.ret)])
		print signature_str
		self.ret['signature'] = hashlib.sha1(signature_str).hexdigest()

		return self.ret
